package com.ityy.ruiji.controller;


import com.ityy.ruiji.common.R;
import com.ityy.ruiji.entity.AddressBook;
import com.ityy.ruiji.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 查询地址
     * @param addressBook
     * @return
     */
    @GetMapping("/list")
    public R list(AddressBook addressBook){
       R result =  addressBookService.finAll(addressBook);
       return result;
    }

    /**
     * 更改默认值
     * @return
     */
    @PutMapping("/default")
    public R defaul(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        R result = addressBookService.defaul(addressBook);
        return result;
    }

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @PostMapping
    public R save(@RequestBody AddressBook addressBook, HttpSession httpSession){
        Long user = (Long) httpSession.getAttribute("user");
        addressBook.setUserId(user);
        addressBook.setCreateUser(user);
        addressBook.setUpdateUser(user);
        R result = addressBookService.save(addressBook);
        return result;
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @GetMapping ("{id}")
    public R get(@PathVariable Long id){
       R<AddressBook> result = addressBookService.finById(id);
       return result;
    }

    /**
     * 修改地址
     * @param addressBook
     * @param httpSession
     * @return
     */
    @PutMapping
    public R update(@RequestBody AddressBook addressBook, HttpSession httpSession){
        Long user = (Long) httpSession.getAttribute("user");
        addressBook.setUpdateUser(user);
        R result = addressBookService.update(addressBook);
        return result;
    }

    /**
     * 根据id删除地址
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteById(Long ids){
        R result = addressBookService.deleteById(ids);
        return result;
    }

    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public R<AddressBook> getDefault(HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        AddressBook addressBook = addressBookService.getDefaultAddress(userId);

        if (null == addressBook) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }
}
